package com.wsm.kotlintest.fragment

import android.view.View
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.wsm.kotlintest.adapter.HomeFragmentContentAdapter
import com.wsm.kotlintest.model.datafactory.DataMaker
import com.wsm.kotlintest.kotlintest2.R
import com.wsm.kotlintest.kotlintest2.databinding.FragmentDataBinding
import com.wsm.kotlintest.viewmodel.fragment.DataFragmentViewModel
import com.wsm.kotlintest.viewmodel.ui.RetryCallBack

class DataFragment : BaseFragment<FragmentDataBinding, DataFragmentViewModel>(DataFragmentViewModel::class.java) {

    companion object {
        fun newInstance() = DataFragment()
    }

    var refreshLayout: SwipeRefreshLayout? = null

    override fun onBindView(view: View) {
        val recyclerView = view.findViewById<RecyclerView>(R.id.rv_content)
        val adapter = HomeFragmentContentAdapter(object : RetryCallBack {
            override fun retryOnLoadMore() {
                (viewModel.dataList.value?.dataSource as DataMaker.MyData).retryWhenLoadMore()
            }
        }, viewModel.loadMoreState, this)
        recyclerView.adapter = adapter
        recyclerView.layoutManager = LinearLayoutManager(activity)

        viewModel.dataList.observe(this, Observer { adapter.submitList(it) })

        refreshLayout = (view.findViewById(R.id.refresh_layout) as SwipeRefreshLayout).apply {
            isRefreshing = true
            setOnRefreshListener { (viewModel.dataList.value?.dataSource as DataMaker.MyData).invalidate() }
            viewModel.isRefreshing.observe(this@DataFragment, Observer { isRefreshing = it })
        }
    }

    override fun setLayout(): Int {
        return R.layout.fragment_data
    }

    override fun doSomething() {
    }

    override fun inject() {
        binding?.vm = viewModel
    }

}